package me.maiz.trainning.devsuggestions.qiniuupload;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.InputStream;

public class QiniuUtil {

    //设置识别用的各种KEY
    private static final String ACCESS_KEY = "你自己的ak";
    private static final String SECRET_KEY = "你自己的sk";
    private static final String BUCKET = "你自己的空间名称";

    public static void upload(String fileKey, InputStream fileStream) {
        //提供配置信息
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);

        Response response = null;
        try {
            //上传
            response = uploadManager.put(fileStream, fileKey, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException e) {
            throw new RuntimeException("上传文件出错",e);
        }
    }

    private static final String CDN_DOMAIN = "你自己的CDN测试域名";

    //生成用于全局访问的网络地址，实际应用时可以直接存入数据库
    public static String fullPath(String fileKey){
        return CDN_DOMAIN+fileKey;
    }

}
